package org.locker.device.controller.admin;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.amazonaws.util.IOUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.locker.common.core.domain.R;
import org.locker.common.core.validate.AddGroup;
import org.locker.common.core.validate.EditGroup;
import org.locker.common.excel.utils.ExcelUtil;
import org.locker.common.idempotent.annotation.RepeatSubmit;
import org.locker.common.log.annotation.Log;
import org.locker.common.log.enums.BusinessType;
import org.locker.common.mybatis.core.page.PageQuery;
import org.locker.common.web.core.BaseController;
import org.locker.domain.bo.DeviceBo;
import org.locker.domain.bo.DeviceOperDommandBo;
import org.locker.domain.enums.DeviceTypeEnum;
import org.locker.domain.vo.DeviceVo;
import org.locker.netty.MachineService;
import org.locker.service.IDeviceService;
import org.springframework.core.io.ResourceLoader;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 设备信息
 *
 * @author winnie
 * @date 2023-10-11
 */
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/device/device")
public class DeviceController extends BaseController {

    private final IDeviceService deviceService;
    private final MachineService machineService;
    private final ResourceLoader resourceLoader;

    /**
     * 查询设备信息列表
     */
    @SaCheckPermission("device:device:list")
    @GetMapping("/list")
    public R<Page<DeviceVo>> list(DeviceBo bo, PageQuery pageQuery) {
        return R.ok(deviceService.queryPageList(bo, pageQuery));
    }

    /**
     * 导出设备信息列表
     */
    @SaCheckPermission("device:device:export")
    @Log(title = "设备信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(DeviceBo bo, HttpServletResponse response) {
        List<DeviceVo> list = deviceService.queryList(bo);
        ExcelUtil.exportExcel(list, "设备信息", DeviceVo.class, response);
    }

    /**
     * 获取设备信息详细信息
     *
     * @param deviceId 主键
     */
    @SaCheckPermission("device:device:query")
    @GetMapping("/{deviceId}")
    public R<DeviceVo> getInfo(@NotNull(message = "主键不能为空")
                               @PathVariable Long deviceId) {
        return R.ok(deviceService.queryById(deviceId));
    }

    /**
     * 获取设备信息详细信息
     *
     * @param positionId 主键
     */
    @GetMapping("/queryByPositionId/{positionId}")
    public R<List<DeviceVo>> queryByPositionId(@NotNull(message = "positionId不能为空")
                                               @PathVariable Long positionId) {
        return R.ok(deviceService.queryByPositionId(positionId));
    }


    /**
     * 新增设备信息
     */
    @SaCheckPermission("device:device:add")
    @Log(title = "设备信息", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody DeviceBo bo) {
        return toAjax(deviceService.insertByBo(bo));
    }

    /**
     * 修改设备信息
     */
    @SaCheckPermission("device:device:edit")
    @Log(title = "设备信息", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody DeviceBo bo) {
        return toAjax(deviceService.updateByBo(bo));
    }

    /**
     * 删除设备信息
     *
     * @param deviceIds 主键串
     */
    @SaCheckPermission("device:device:remove")
    @Log(title = "设备信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{deviceIds}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] deviceIds) {
        return toAjax(deviceService.deleteWithValidByIds(List.of(deviceIds), true));
    }

    /**
     * 生成设备二维码
     *
     * @param deviceNo
     * @return
     */
    @GetMapping("/createQrcode")
    public R createQrcode(@RequestParam("deviceNo") String deviceNo) {
        deviceService.createQrcode(deviceNo);
        return R.ok();
    }

    /**
     * 生成公众号二维码
     *
     * @param deviceNo
     * @return
     */
    @GetMapping("/createMpQrcode")
    public R createMpQrcode(@RequestParam("deviceNo") String deviceNo) {
        deviceService.createMpQrcode(deviceNo);
        return R.ok();
    }


    /**
     * 设备指令
     *
     * @param operDommandBo
     * @return
     */
    @PostMapping("/operDommand")
    public R operDommand(@Validated @RequestBody DeviceOperDommandBo operDommandBo) {
        String code = operDommandBo.getOperType();
        String deviceNo = operDommandBo.getDeviceNo();
        switch (code) {
            case "2" -> {
                machineService.restartDevice(deviceNo);
            }
            case "3" -> {
                machineService.setDevicePosition(deviceNo);
            }
            case "4" -> {
                machineService.controlOpenAll(deviceNo);
            }
            case "5" -> {
                machineService.synchronousGridList(deviceNo);
            }
            case "6" -> {
                machineService.batchSetGrid(deviceNo);

            }
            case "7" -> {
                machineService.deviceCommonInfoSync(deviceNo);

            }
//            case "8" -> {
//                boolean open = false;
//                if (openCode.equals("true")) {
//                    open = true;
//                }
//                machineService.controlBleSwitch(deviceNo, blueMac, open);
//            }
            case "9" -> {
                machineService.upgradeBle(deviceNo);

            }
            case "11" -> {
                machineService.orderListSync(deviceNo);
            }
            case "12" -> {
                machineService.getSimInfo(deviceNo);

            }
            case "13" -> {
                machineService.adminExec(deviceNo);

            }
            case "14" -> {
                machineService.modifyAdminAccount(deviceNo);

            }
            case "15" -> {
                machineService.uploadDeviceLog(deviceNo);

            }
            case "16" -> {
                machineService.deletedDeviceLog(deviceNo);

            }
            default -> throw new IllegalStateException("Unexpected deviceNo: " + code);
        }
        return R.ok();
    }

    /**
     * 导入格子信息
     *
     * @return
     */
    @PostMapping("/importGrid")
    public R importGrid(@RequestPart("file") MultipartFile file, @RequestParam("deviceNo") String deviceNo) {
        deviceService.importGrid(file, deviceNo);
        return R.ok();
    }

    /**
     * 获取蓝牙设备格子导入模板
     */
    @PostMapping("/importTemplate/{deviceType}")
    public void importTemplate(@PathVariable String deviceType, HttpServletResponse response) throws Exception {
        String fileName = "串口设备-柜子导入模版.xlsx";
        if (DeviceTypeEnum.BLUETOOTH.getCode().equalsIgnoreCase(deviceType)) {
            //蓝牙设备
            fileName = "蓝牙设备-柜子导入模版.xlsx";
        }
        InputStream is = null;
        OutputStream os = null;
        try {
            is = this.getClass().getClassLoader().getResourceAsStream(File.separator+fileName);
            os = response.getOutputStream();
            byte[] bytes = IOUtils.toByteArray(is);
            response.reset();
            //下面这两行是为了解决跨域，如果没有跨域这两行可以删除
            response.addHeader("Access-Control-Allow-Origin", "*");
            response.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
            response.setContentType("application/octet-stream;charset=utf-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1));
            response.addHeader("Content-Length", "" + bytes.length);
            os.write(bytes);
            os.flush();
        }catch (Exception e) {
            log.error("下载出错", e);
        }finally {
            try {
                if(os != null) {
                    os.close();
                }
                if (is != null) {
                    is.close();
                }
            }catch (Exception e) {
                log.error("关闭流出错", e);
            }
        }
    }
}
